package com.css.project.oa.travel.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.css.common.utils.Arith;
import com.css.common.utils.ConvertNumberToUpperUtils;
import com.css.common.utils.SecurityUtils;
import com.css.common.utils.StringUtils;
import com.css.framework.aspectj.lang.annotation.DataScope;
import com.css.framework.security.LoginUser;
import com.css.project.oa.fileInfo.domain.SysFileInfo;
import com.css.project.oa.fileInfo.mapper.SysFileInfoMapper;
import com.css.project.oa.travel.domain.Travel;
import com.css.project.oa.travel.domain.TravelItem;
import com.css.project.oa.travel.domain.TravelItemMain;
import com.css.project.oa.travel.domain.TravelPrint;
import com.css.project.oa.travel.mapper.TravelItemMainMapper;
import com.css.project.oa.travel.mapper.TravelItemMapper;
import com.css.project.oa.travel.mapper.TravelMapper;
import com.css.project.oa.travel.service.ITravelService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class TravelServiceImpl implements ITravelService {

    @Autowired
    public TravelMapper travelMapper;

    @Autowired
    public TravelItemMainMapper travelItemMainMapper;

    @Autowired
    public TravelItemMapper travelItemMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    public SysFileInfoMapper sysFileInfoMapper;

    @Override
    @DataScope(deptAlias = "d",userAlias="u" )
    public List<Travel> getTravelList(Travel travel) {
        List<Travel> list = travelMapper.getTravelList(travel) ;
        for(Travel model : list){
            if(StringUtils.isNotEmpty(model.getInstanceId())){
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(model.getInstanceId())
                        .list();    // 万一有多个
                if (!CollectionUtils.isEmpty(taskList)) {
                    Task task = taskList.get(0);
                    model.setTaskId(task.getId());
                    model.setTaskName(task.getName());
                } else {
                    model.setTaskName("已办结");
                }
            }else{
                model.setTaskName("未上报");
            }
        }
        return list ;
    }
    /*
     *itemsJson往返车票
     * items1Json打车票/住宿票
     * */
    @Override
    @Transactional
    public Long add(Travel travel, String itemsJson, String items1Json) {
        LoginUser cu = SecurityUtils.getLoginUser();
        travel.setCreateTime(new Date());
        travel.setCreateBy(cu.getUsername());
        travel.setUpdateTime(new Date());
        travel.setUpdateBy(cu.getUsername());
        travel.setDelFlag("0");
        travel.setBelongId(cu.getUser().getUserId());
        travelMapper.insertTravel(travel);
        this.AddMainAndItem(travel,itemsJson,items1Json);
        return travel.getTravelId() ;
    }

    public void AddMainAndItem(Travel travel, String itemsJson, String items1Json){
        LoginUser cu = SecurityUtils.getLoginUser();
        List<TravelItemMain> itemList = JSON.parseArray(itemsJson, TravelItemMain.class);
        Double moneySum = 0D;
        for (TravelItemMain travelItemMain : itemList) {
            travelItemMain.setTravelId(travel.getTravelId());
            travelItemMainMapper.insertTravelItemMain(travelItemMain) ;
            moneySum = Arith.add(moneySum, travelItemMain.getTravelAllowance());
            //附件
            String fileListStr = travelItemMain.getFileList();
            if(StringUtils.isNotEmpty(fileListStr)) {
                List<Map> fileMapList =  JSON.parseArray(fileListStr, Map.class);
                for(Map<String, Object> map : fileMapList){
                    SysFileInfo fileInfo = new SysFileInfo();
                    fileInfo.setName(map.get("name").toString());
                    fileInfo.setFilePath(map.get("fileName").toString());
                    fileInfo.setFileSize(map.get("size").toString());
                    fileInfo.setInfoTable("pro_travel_item_main");
                    fileInfo.setInfoId(travelItemMain.getTravelItemMainId());
                    fileInfo.setUploadUser(cu.getUsername());
                    fileInfo.setUploadTime(new Date());
                    sysFileInfoMapper.insertSysFileInfo(fileInfo);
                }
            }

            List<TravelItem> TravelItemList = travelItemMain.getChangeTravelItemList() ;//往返车票
            for (TravelItem travelItem : TravelItemList) {
                moneySum = Arith.add(moneySum, travelItem.getExpenseMoney());
                travelItem.setTravelId(travel.getTravelId());
                travelItem.setTravelItemMainId(travelItemMain.getTravelItemMainId());
                travelItem.setExpenseContent("火车票");
                travelItem.setTravelType("1") ;//类型1差旅票2打车票3住宿票
                travelItemMapper.insertTravelItem(travelItem) ;
            }
        }
        if(StringUtils.isNotEmpty(items1Json)) {//打车票
            List<TravelItem> item1List = JSON.parseArray(items1Json, TravelItem.class);
            for (TravelItem travelItem : item1List) {
                moneySum = Arith.add(moneySum, travelItem.getExpenseMoney());
                travelItem.setTravelId(travel.getTravelId());
                //类型1差旅票2打车票3住宿票
                if(travelItem.getTravelType().equals("2")){
                    travelItem.setExpenseContent("出租车票");
                }else if(travelItem.getTravelType().equals("3")){
                    travelItem.setExpenseContent("住宿票");
                }
                travelItemMapper.insertTravelItem(travelItem) ;
                //附件
                String fileListStr = travelItem.getFileList();
                if(StringUtils.isNotEmpty(fileListStr)) {
                    List<Map> fileMapList =  JSON.parseArray(fileListStr, Map.class);
                    for(Map<String, Object> map : fileMapList){
                        SysFileInfo fileInfo = new SysFileInfo();
                        fileInfo.setName(map.get("name").toString());
                        fileInfo.setFilePath(map.get("fileName").toString());
                        fileInfo.setFileSize(map.get("size").toString());
                        fileInfo.setInfoTable("pro_travel_item");
                        fileInfo.setInfoId(travelItem.getTravelItemId());
                        fileInfo.setUploadUser(cu.getUsername());
                        fileInfo.setUploadTime(new Date());
                        sysFileInfoMapper.insertSysFileInfo(fileInfo);
                    }
                }
            }
        }
        Travel updateTravel = new Travel() ;
        updateTravel.setTravelId(travel.getTravelId());
        updateTravel.setTotalAmount(moneySum);
        updateTravel.setTotalAmountUpper(Convert.digitToChinese(moneySum));
        //更新报销单的总金额
        travelMapper.updateTravel(updateTravel) ;
    }

    @Override
    @Transactional
    public Long update(Travel travel, String itemsJson, String items1Json) {
        LoginUser cu = SecurityUtils.getLoginUser();
        travel.setUpdateTime(new Date());
        travel.setUpdateBy(cu.getUsername());
        travelMapper.updateTravel(travel);
        travelItemMainMapper.deleteTravelItemMain(travel.getTravelId()) ;
        travelItemMapper.deleteTravelItem(travel.getTravelId()) ;
        this.AddMainAndItem(travel,itemsJson,items1Json);
        return travel.getTravelId() ;
    }

    @Override
    public int deleteTravel(Long[] travelIds) {
        LoginUser cu = SecurityUtils.getLoginUser();
        Travel travel = new Travel() ;
        travel.setUpdateTime(new Date());
        travel.setUpdateBy(cu.getUsername());

        for(Long travelId:travelIds){
            travel.setTravelId(travelId);
            travelMapper.deleteTravel(travel);
        }
        return 1;
    }

    @Override
    public Map<String, Object> getTravelById(Long travelId) {
        Map<String, Object> map = new HashMap<String, Object>();
        Travel travel = travelMapper.getTravelById(travelId);
        List<TravelItemMain> itemMainList  = travelItemMainMapper.getTravelMainByTravelId(travel.getTravelId());
        for(TravelItemMain itemMain :itemMainList){
            itemMain.setChangeTravelItemList(travelItemMapper.getTravelItemByMainId(itemMain.getTravelItemMainId()));
            SysFileInfo info = new SysFileInfo();
            info.setInfoTable("pro_travel_item_main");
            info.setInfoId(itemMain.getTravelItemMainId());
            itemMain.setFileInfoList(sysFileInfoMapper.selectSysFileInfoList(info));
        }
        List<TravelItem> itemTaxiList= travelItemMapper.getTravelTaxiItemByTravelId(travelId) ;
        for(TravelItem itemTaxi :itemTaxiList){
            SysFileInfo info = new SysFileInfo();
            info.setInfoTable("pro_travel_item");
            info.setInfoId(itemTaxi.getTravelItemId());
            itemTaxi.setFileInfoList(sysFileInfoMapper.selectSysFileInfoList(info));
        }
        map.put("travelDomain", travel);
        map.put("itemMainDomain", itemMainList);
        map.put("itemTaxiDomain", itemTaxiList);
        return map;
    }
    /**
     *	 获取差旅打印主信息
     */
	@Override
	public TravelPrint getMainTravelPrint(Long travelId) {
		// TODO Auto-generated method stub
		return travelMapper.getMainTravelPrint(travelId);
	}
	/**
	   *  获取差旅报销单打印列表
	 */
	@Override
	public List<TravelPrint> getTravelPrintList(Long travelId) {
		// TODO Auto-generated method stub
		List<TravelPrint> finalList = new ArrayList<TravelPrint>();
		List<TravelPrint> list = travelItemMapper.getTravelPrintList(travelId);
		TravelItem travelItemParam = new TravelItem();
		travelItemParam.setTravelId(travelId);
		if(list != null) {
			//按照报销单格式，补全信息
			if(list.size() == 1) {
				TravelPrint travelPrint = list.get(0);
				TravelItemMain travelItemMain = travelItemMainMapper.selectById(travelPrint.getTravelItemMainId());
				travelPrint.setDays(travelItemMain.getTravelNum());
				travelPrint.setBtMoney(travelItemMain.getTravelAllowance());
				travelPrint.setOtherCostName("住  宿  费");
				travelItemParam.setTravelType("3");
				TravelItem zs = travelItemMapper.getTravelItemSum(travelItemParam);
				if(zs != null) {
					travelPrint.setOtherInvoiceNum(zs.getInvoiceNum());
					travelPrint.setOtherExpenseMoney(zs.getExpenseMoney());
				}
				finalList.add(travelPrint);
				//补空行
				TravelPrint tmp;
				for(int i=1;i<6;i++) {
					tmp = new TravelPrint();
					if(i==1) {
						tmp.setOtherCostName("市 内 车 费");
						travelItemParam.setTravelType("2");
						TravelItem dc = travelItemMapper.getTravelItemSum(travelItemParam);
						if(dc != null) {
							tmp.setOtherInvoiceNum(dc.getInvoiceNum());
							tmp.setOtherExpenseMoney(dc.getExpenseMoney());
						}
						finalList.add(tmp);
					}else if(i==2) {
						tmp.setOtherCostName("其他");
						tmp.setOtherInvoiceNum(0);
						tmp.setOtherExpenseMoney(0.0);
						finalList.add(tmp);
					}else {
						finalList.add(new TravelPrint());
					}
				}
			}else if(list.size() == 2) {
				TravelPrint travelPrint = list.get(0);
				TravelPrint travelPrint1 = list.get(1);
				if(travelPrint.getTravelItemMainId() != travelPrint1.getTravelItemMainId()) {
					//不同组出差
					TravelItemMain travelItemMain = travelItemMainMapper.selectById(travelPrint.getTravelItemMainId());
					travelPrint.setDays(travelItemMain.getTravelNum());
					travelPrint.setBtMoney(travelItemMain.getTravelAllowance());
					TravelItemMain travelItemMain1 = travelItemMainMapper.selectById(travelPrint1.getTravelItemMainId());
					travelPrint1.setDays(travelItemMain1.getTravelNum());
					travelPrint1.setBtMoney(travelItemMain1.getTravelAllowance());
				}else {
					TravelItemMain travelItemMain1 = travelItemMainMapper.selectById(travelPrint1.getTravelItemMainId());
					travelPrint1.setDays(travelItemMain1.getTravelNum());
					travelPrint1.setBtMoney(travelItemMain1.getTravelAllowance());
				}
				travelPrint.setOtherCostName("住  宿  费");
				travelItemParam.setTravelType("3");
				TravelItem zs = travelItemMapper.getTravelItemSum(travelItemParam);
				if(zs != null) {
					travelPrint.setOtherInvoiceNum(zs.getInvoiceNum());
					travelPrint.setOtherExpenseMoney(zs.getExpenseMoney());
				}
				finalList.add(travelPrint);
				travelPrint1.setOtherCostName("市 内 车 费");
				travelItemParam.setTravelType("2");
				TravelItem dc = travelItemMapper.getTravelItemSum(travelItemParam);
				if(dc != null) {
					travelPrint1.setOtherInvoiceNum(dc.getInvoiceNum());
					travelPrint1.setOtherExpenseMoney(dc.getExpenseMoney());
				}
				finalList.add(travelPrint1);
				//补空行
				TravelPrint tmp;
				for(int i=1;i<5;i++) {
					tmp = new TravelPrint();
					if(i==1) {
						tmp.setOtherCostName("其他");
						tmp.setOtherInvoiceNum(0);
						tmp.setOtherExpenseMoney(0.0);
						finalList.add(tmp);
					}else {
						finalList.add(new TravelPrint());
					}
				}
			}else {
				Long travelItemMainId = null;//记录一组出差的标识id
				for(int i=0;i<list.size();i++) {
					TravelPrint travelPrint = list.get(i);
					if(i==0) {
						travelPrint.setOtherCostName("住  宿  费");
						travelItemParam.setTravelType("3");
						TravelItem zs = travelItemMapper.getTravelItemSum(travelItemParam);
						if(zs!=null) {
							travelPrint.setOtherInvoiceNum(zs.getInvoiceNum());
							travelPrint.setOtherExpenseMoney(zs.getExpenseMoney());
						}
					}else if(i==1) {
						travelPrint.setOtherCostName("市 内 车 费");
						travelItemParam.setTravelType("2");
						TravelItem dc = travelItemMapper.getTravelItemSum(travelItemParam);
						if(dc!= null) {
							travelPrint.setOtherInvoiceNum(dc.getInvoiceNum());
							travelPrint.setOtherExpenseMoney(dc.getExpenseMoney());
						}
					}else if(i==2) {
						travelPrint.setOtherCostName("其他");
						travelPrint.setOtherInvoiceNum(0);
						travelPrint.setOtherExpenseMoney(0.0);
					}
					//补充出差补贴
					travelItemMainId = travelPrint.getTravelItemMainId();
					boolean getTravelItemMain = false;
					if(i==list.size()-1) {
						//最后一条数据,补上出差补贴信息
						getTravelItemMain = true;
					}else {
						if(travelItemMainId != list.get(i+1).getTravelItemMainId()) {
							//如果下一条数据的travelItemMainId与当前不一致，则说明不是一组，当前数据
							//补上出差补贴信息
							getTravelItemMain = true;
						}
					}
					if(getTravelItemMain) {
						TravelItemMain travelItemMain = travelItemMainMapper.selectById(travelPrint.getTravelItemMainId());
						travelPrint.setDays(travelItemMain.getTravelNum());
						travelPrint.setBtMoney(travelItemMain.getTravelAllowance());
					}
					finalList.add(travelPrint);
				}
				//补空行
				for(int j=0;j<(6-list.size());j++) {
					finalList.add(new TravelPrint());
				}
			}
			
		}
		return finalList;
	}
	/**
	   *  获取差旅报销明细打印列表
	 */
	@Override
	public List<TravelPrint> getTravelPrintMxList(Long travelId) {
		// TODO Auto-generated method stub
		return travelItemMapper.getTravelPrintMxList(travelId);
	}

}
